<template>
  <el-select
    clearable
    v-model="keyWord"
    multiple
    collapse-tags
    fit-input-width
    filterable
    :max-collapse-tag="8"
    allow-create
    :reserve-keyword="false"
    @paste="v => handlerPaster(v)"
    @clear="onReset"
    @change="handlerChange"
    @blur="handlerBlur"
    default-first-option
    placeholder="支持复制或输入关键词"
  >
    <el-option
      v-for="item in batchTags"
      :key="item"
      :label="item"
      :value="item"
    />
  </el-select>
</template>
<script setup>
import { FIRST_LAST_KEYS } from 'element-plus'
import { ref } from 'vue'
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  }
})
const emits = defineEmits(['update:modelValue'])
const batchTags = ref(props.modelValue)
const keyWord = ref([])
const isPaste = ref(false)
// 批量查询输入失去焦点
const handlerPaster = event => {
  const clipboardData = event.clipboardData || window.clipboardData
  const pastedText = clipboardData.getData('text')
  const valueStr = pastedText.replaceAll(/\t|\n|\s+/g, ' ')
  const values = valueStr.split(' ').filter(item => {
    return item.trim() !== ''
  })
  if (!batchTags.value) {
    batchTags.value = []
  }
  batchTags.value = Array.from(new Set([...values, ...batchTags.value]))
  keyWord.value = batchTags.value
  isPaste.value = true
  emits('update:modelValue', batchTags.value)
}
const handlerChange = () => {
  batchTags.value = keyWord.value

  emits('update:modelValue', batchTags.value)
}
const handlerBlur = e => {
  if (isPaste.value) {
    isPaste.value = false
    return false
  }
  const v = e.target.value
  v && keyWord.value.push(v)
  handlerChange()
}
const onReset = () => {
  keyWord.value = []
  batchTags.value = []
  emits('update:modelValue', batchTags.value)
}
</script>
<style lang="scss" scoped></style>
